// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: gekim

#pragma once

#include <string>

#include <rapidjson/document.h>
#include <rapidjson/rapidjson.h>

#include "coin/proto/coin_market_enums.pb.h"
#include "coin2/base/conversion.h"
#include "coin2/exchange/base/feed/update.h"
#include "coin2/exchange/base/feed_util/book_builder.h"
#include "coin2/exchange/base/feed_util/trade.h"

namespace impl {
namespace {
const int kConsecutiveZeroSizeThreshold = 3;
}  // namespace
using coin2::exchange::base::market::ExchangeType;
using coin2::exchange::base::market::MarketType;

class BitbankFeedUpdateParser {
 public:
  static bool
  ParseSnapshot(BookBuilder* book_builder_, const rapidjson::Value& book_json, int64_t timestamp) {
    auto tx = book_builder_->NewTransaction(timestamp);

    for (const auto& ask_obj : book_json["asks"].GetArray()) {
      auto ask_array = ask_obj.GetArray();
      double price = stod(ask_array[0].GetString());
      double size = stod(ask_array[1].GetString());
      tx.UpdateAsk(price, size);
    }

    for (const auto& bid_obj : book_json["bids"].GetArray()) {
      auto bid_array = bid_obj.GetArray();
      double price = stod(bid_array[0].GetString());
      double size = stod(bid_array[1].GetString());
      tx.UpdateBid(price, size);
    }

    if (book_builder_->AskSize() == 0 || book_builder_->BidSize() == 0) {
      tx.Clear();
      return false;
    }
    return true;
  }

  static bool
  ParseUpdate(BookBuilder* book_builder_, const rapidjson::Value& book_json, int64_t timestamp) {
    auto tx = book_builder_->NewTransaction(timestamp);

    if (book_json.HasMember("a")) {
      for (const auto& ask_obj : book_json["a"].GetArray()) {
        auto ask_array = ask_obj.GetArray();
        double price = stod(ask_array[0].GetString());
        double size = stod(ask_array[1].GetString());
        tx.UpdateAsk(price, size);
      }
    }

    if (book_json.HasMember("b")) {
      for (const auto& bid_obj : book_json["b"].GetArray()) {
        auto bid_array = bid_obj.GetArray();
        double price = stod(bid_array[0].GetString());
        double size = stod(bid_array[1].GetString());
        tx.UpdateBid(price, size);
      }
    }

    if (book_builder_->AskSize() == 0 || book_builder_->BidSize() == 0) {
      tx.Clear();
      return false;
    }
    return true;
  }

  static void ParseTrade(const rapidjson::Value& trade_json, Trade* trade) {
    trade->price = stod(trade_json["price"].GetString());
    trade->fill_qty = stod(trade_json["amount"].GetString());
    trade->side = ParseTradeSide(trade_json["side"].GetString());
    trade->timestamp =
        static_cast<int64_t>(trade_json["executed_at"].GetInt64() * 1'000'000LL);
  }

  static coin2::exchange::feed::TradeSide ParseTradeSide(const std::string& side) {
    if (side == "buy") {
      return coin2::exchange::feed::TRADE_BUY_SIDE;
    } else if (side == "sell") {
      return coin2::exchange::feed::TRADE_SELL_SIDE;
    } else if (side.empty()) {
      return coin2::exchange::feed::TRADE_NO_SIDE;
    } else {
      throw std::runtime_error("[Bitbank] unknown side: " + side);
    }
  }

  static bool Parse1Kline(
      const rapidjson::Value& kline_data,
      Klines* klines,
      int64_t timestamp,
      fastfeed::proto::KlineInterval interval) {
    CHECK_EQ(kline_data.Size(), 6);
    int64_t open_timestamp = kline_data[5].GetInt64() * 1'000'000LL;
    auto result = klines->AddKline(open_timestamp);
    if (!result) return false;

    Kline* kline;
    bool freezed;
    std::tie(kline, freezed) = result.value();

    kline->open = stod(kline_data[0].GetString());
    kline->high = stod(kline_data[1].GetString());
    kline->low = stod(kline_data[2].GetString());
    kline->close = stod(kline_data[3].GetString());
    kline->volume = stod(kline_data[4].GetString());
    kline->timestamp = timestamp;
    kline->interval = interval;
    return freezed;
  }

  static fastfeed::proto::KlineInterval ParseKlineInterval(const std::string& period) {
    static std::map<std::string, fastfeed::proto::KlineInterval> interval_map = {
      {"1min", fastfeed::proto::KLINE_INTERVAL_1MIN},
      {"5min", fastfeed::proto::KLINE_INTERVAL_5MIN},
      {"15min", fastfeed::proto::KLINE_INTERVAL_15MIN},
      {"30mim", fastfeed::proto::KLINE_INTERVAL_30MIN},
      {"1hour", fastfeed::proto::KLINE_INTERVAL_1HOUR},
      {"4hour", fastfeed::proto::KLINE_INTERVAL_4HOUR},
      {"8hour", fastfeed::proto::KLINE_INTERVAL_8HOUR},
      {"12hour", fastfeed::proto::KLINE_INTERVAL_12HOUR},
      {"1day", fastfeed::proto::KLINE_INTERVAL_1DAY},
      {"1week", fastfeed::proto::KLINE_INTERVAL_1WEEK},
      {"1month", fastfeed::proto::KLINE_INTERVAL_1MON}
    };
    auto iter = interval_map.find(period);
    if (iter == interval_map.end()) {
      
      return fastfeed::proto::KLINE_INTERVAL_INVALID;
    }

    return iter->second;
  }

};
}  // namespace impl

using impl::BitbankFeedUpdateParser;
